import Vue from "vue";
import Router from "vue-router";
import layout from "../views/layout/layout";
import request from '../utils/request';
import {
  JWT_TOKEN
} from "../config/constants";
Vue.use(Router);


// const _import = file=>resolve => require(['../views/'+file], resolve);

const _import = (file) => {
  return () => System.import('@/views/' + file + '.vue')
}


function getUrlParam(name) {  
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");  
  var r = window.location.search.substr(1).match(reg);  
  if (r != null) return unescape(r[2]);  
  return null;
}

let router = new Router({
  hashbang: true,
  // mode: "history",
  saveScrollPosition: true,
  routes: [{
      path: "/",
      redirect: "/home",
      component: layout,
      children: [{
        path: "index",
        component: _import("index/index")
      }]
    },
    {
      path: "/center",
      component: _import("home/index"),
      meta: {
        title: '个人中心'
      }
    },
    {
      path: "/paycar",
      component: _import("other/paycar"),
      meta: {
        title: '支付卡管理'
      }
    },
    {
      path: "/home",
      component: _import("home/home"),
      meta: {
        title: '会员中心'
      }
    },
    {
      path: "/reback",
      component: _import("reback/index"),
      meta: {
        title: '申请退款退款'
      }
    },
    {
      path: "/rebackstep",
      component: _import("reback/step"),
      meta: {
        title: '退款详情'
      }
    },
    {
      path: "/rebackdetail",
      component: _import("reback/detail"),
      meta: {
        title: '申请退款'
      }
    },
    {
      path: "/question",
      component: _import("index/question")
    },
    {
      path: "/mymsg",
      component: _import('home/mymsg'),
      meta: {
        title: '我的消息'
      }
    },
    {
      path: "/msgdetail",
      component: _import('home/msgdetail'),
      meta: {
        title: '消息详情'
      }
    },
    {
      path: "/bindsolidcard",
      component: _import('home/bindsolidcard'),
      meta: {
        title: '绑定实体积分卡'
      }
    },
    {
      path: "/car",
      component: _import('other/car'),
      meta: {
        title: '车辆信息管理'
      }
    },
    {
      path: "/carlicence",
      component: _import('other/carlicence'),
      meta: {
        title: '车牌付设置'
      }
    },
    {
      path: "/feedback",
      component: _import('index/feedback'),
      meta: {
        title: '留言反馈'
      }
    },
    {
      path: "/tj",
      component: _import('shop/index'),
      meta: {
        title: '特价商品',
        tj: true
      }
    },
    {
      path: "/customer_service",
      component: _import('index/customer_service'),
      meta: {
        title: '客服中心'
      }
    },
    {
      path: "/oillist",
      component: _import('oil/list'),
      meta: {
        title: '查找油站'
      }
    },
    {
      path: "/oil/search",
      component: _import('oil/search'),
      meta: {
        title: '查找油站'
      }
    },
    {
      path: "/dzj",
      component: _import('dzj/list'),
      meta: {
        title: '我的电子券'
      }
    },
    {
      path: "/yh",
      component: _import('yh/list'),
      meta: {
        title: '我的优惠券'
      }
    },
    {
      path: "/dzjdetail",
      component: _import('dzj/detail'),
      meta: {
        title: '我的电子券'
      }
    },
    {
      path: "/bill",
      component: _import('bill/index'),
      meta: {
        title: '订单管理'
      }
    },
    {
      path: "/surebill/:cartIds",
      component: _import('cart/surebill'),
      meta: {
        title: '订单确认'
      }
    },
    {
      path: "/register",
      component: _import('home/register'),
      meta: {
        title: '注册登录'
      }
    },
    {
      path: "/billdetail",
      component: _import('bill/detail'),
      meta: {
        title: '订单详情'
      }
    },
    {
      path: "/comment",
      component: _import('bill/comment'),
      meta: {
        title: '发表评论'
      }
    },
    {
      path: "/cart",
      component: _import('cart/index'),
      meta: {
        title: '购物车'
      }
    },
    {
      path: "/userinfo",
      component: _import('userinfo/index'),
      meta: {
        title: '会员说明'
      }
    },
    {
      path: "/goodsdetail",
      component: _import('goods/detail'),
      meta: {
        title: '商品详情'
      }
    },
    {
      path: "/shop",
      component: _import('shop/index'),
      meta: {
        title: '会员商城'
      }
    },
    {
      path: "/xsqg",
      component: _import('shop/xsqg'),
      meta: {
        title: '限时抢购'
      }
    },
    {
      path: "/xsqging",
      component: _import('shop/xsqging'),
      meta: {
        title: '限时抢购'
      }
    },
    {
      path: "/selfpay",
      component: _import('shop/selfpay'),
      meta: {
        title: '自助支付'
      }
    },
    {
      path: "/group",
      component: _import('shop/group'),
      meta: {
        title: '今日拼团'
      }
    },
    {
      path: "/invoice",
      component: _import('shop/invoice'),
      meta: {
        title: '开具发票'
      }
    },
    {
      path: "/invoice_detail",
      component: _import('invoice/detail'),
      meta: {
        title: '开具发票'
      }
    },
    {
      path: "/myinvoices",
      component: _import('home/myinvoices'),
      meta: {
        title: '我的发票'
      }
    },
    {
      path: "/invoicelist",
      component: _import('shop/invoicelist'),
      meta: {
        title: '我的发票'
      }
    },
    {
      path: "/check_login",
      component: _import('login/check'),
      meta: {
        title: '扫码登录确认'
      }
    },
    {
      path: "/feedbackdetail",
      component: _import('index/feedbackdetail'),
      meta: {
        title: '反馈详情'
      }
    },
    {
      path: "/invoicehistory",
      component: _import('shop/invoicehistory'),
      meta: {
        title: '我的发票'
      }
    },
    {
      path: "/invoicemanage",
      component: _import('invoice/manage'),
      meta: {
        title: '发票抬头管理'
      }
    },
    {
      path: "/myinvoicedetail",
      component: _import('invoice/myinvoicedetail'),
      meta: {
        title: '电子开票详情'
      }
    },
    {
      path: "/invoicedetail",
      component: _import('invoice/myinvoicedetail'),
      meta: {
        title: '电子发票详情'
      }
    },
    {
      path: "/invoicepic",
      component: _import('invoice/invoicepic'),
      meta: {
        title: '电子开票详情'
      }
    },
    {
      path: "/invoiceadd",
      component: _import('invoice/add'),
      meta: {
        title: '添加发票信息'
      }
    },
    {
      path: "/feedback_history",
      component: _import('index/feedback_history'),
      meta: {
        title: '留言反馈'
      }
    },
    {
      path: "/album",
      component: _import('album/index'),
      meta: {
        title: '主题专区'
      }
    },
    {
      path: "/addrmgr",
      component: _import('other/addrmgr'),
      meta: {
        title: '收货地址管理'
      }
    },
    {
      path: "/myinvoice",
      component: _import('goods/category'),
      meta: {
        title: '商品分类'
      }
    },
    {
      path: "/mypointscard",
      component: _import('home/mypointscard'),
      meta: {
        title: '我的积分卡'
      }
    },
    {
      path: "/settings",
      component: _import('home/settings'),
      meta: {
        title: '我的设置'
      }
    },
    {
      path: "/collections",
      component: _import('home/mycollection'),
      meta: {
        title: '我的收藏'
      }
    },
    {
      path: "/page",
      component: _import('home/page'),
      meta: {
        title: ''
      }
    },
    {
      path: "/costlist",
      component: _import('cost/list'),
      meta: {
        title: '消费明细'
      }
    },
    {
      path: "/costdetail",
      component: _import('cost/detail'),
      meta: {
        title: '消费详情'
      }
    },
    {
      path: "/goodscomment",
      component: _import('goods/detail'),
      meta: {
        title: '用户评论',
        is_comment: 1
      }
    },
    {
      path: "/sign",
      component: _import('sign/index'),
      meta: {
        title: '签到积分'
      }
    },
    {
      path: "/goodscomment",
      component: _import('goods/comments'),
      meta: {
        title: '用户评论'
      }
    },
    {
      path: "/redbag",
      component: _import('act/redbag'),
      meta: {
        title: '用户评论'
      }
    },
    {
      path: "/paycaradd",
      component: _import('paycar/add'),
      meta: {
        title: '编辑支付卡信息'
      }
    },
    {
      path: "/checklogin",
      component: _import('other/checklogin'),
      meta: {
        title: '登录确认'
      }
    },
    {
      path: "/search",
      component: _import('shop/search'),
      meta: {
        title: '商品搜索'
      }
    },
    {
      path: "/flow",
      component: _import('goods/flow'),
      meta: {
        title: '商品物流'
      }
    },
    {
      path: "/addcar",
      component: _import('other/addcar'),
      meta: {
        title: '添加车辆信息'
      }
    },
    {
      path: "/addradd",
      component: _import('other/addradd'),
      meta: {
        title: '添加收货地址'
      }
    },
    {
      path: "/job",
      component: _import('other/job'),
      meta: {
        title: '添加职业信息'
      }
    },
    {
      path: "/alterphone",
      component: _import('other/alterphone'),
      meta: {
        title: '修改手机号码'
      }
    },
    {
      path: "/findsolidcard",
      component: _import('other/findsolidcard'),
      meta: {
        title: '找回积分实体卡'
      }
    },
    {
      path: "/findsolidcardsuccess",
      component: _import('other/findsolidcardsuccess'),
      meta: {
        title: '找回积分实体卡'
      }
    },
    {
      path: "/question/detail",
      component: _import('index/questiondetail'),
      meta: {
        title: '问题详情'
      }
    }
  ]
});
let whiteListRouter = ['/oillist'];

function getAuthedCode() {
  var code = getUrlParam("code");
  return code;
}

function hasJWT() {
  return !!localStorage.getItem(JWT_TOKEN);
}

function getWechatAuth() {
  // var appId = 'wx504d824d6ecbd37e';
  var appId = APPID;
  // var appId = 'wx101f262d4199b623'; //脑洞筹
  // var appId = 'wx101f262d4199b623';


  let v = location.href;
  v = v.replace(/(&|)code=([^&]+)(&|)/, '');
  localStorage.setItem('returnUrl', v);
  let h = encodeURIComponent(v.split('#')[0]);
  var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + h + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
  window.location.replace(url);
}
router.beforeEach((to, from, next) => {
  // 因为授权登录涉及异步操作，因此使用promise，成功的回调中调用next函数
  new Promise((resolve, rejects) => {
    var found = false;
    for (let i = 0; i < whiteListRouter.length; i++) {
      let path = whiteListRouter[i];      
      if (to.path.startsWith(path)) {
        resolve()
        return
      }
    }
    if (!hasJWT()) {
      let code = getAuthedCode();
      if (code) {
        request({
          url: '/api/wx/login',
          method: 'post',
          data: {
            code
          }
        }).then(info => {
          localStorage.setItem(JWT_TOKEN, info.jwt);
          let returnUrl = localStorage.getItem('returnUrl') || '';
          if (!returnUrl) {
            returnUrl = location.protocol + '//' + location.hostname;
          }
          location.replace(returnUrl);
        });

      } else {
        getWechatAuth();
      }
    } else {
      resolve();
    }
  }).then(res => {
    next()
  })
});
export default router;
